<template>
    <ClientOnly>
        <popup
            :show="visible"
            width="500px"
            title="支付方式"
            confirmButtonText=""
            cancelButtonText=""
            @close="handleClose"
        >
            <div class="p-3 pb-4">
                <div class="px-1 pb-2 flex justify-between">
                    <div v-if="paidAmount" class="text-lg font-bold pb-1.5">
                        应付金额: ¥{{ paidAmount }}
                    </div>
                    <div v-if="productName" class="text-lg font-bold pb-1.5">
                        购买产品: {{ productName }}
                    </div>
                </div>
                <div class="optional-body">
                    <div class="body-sidebar">
                        <div
                            v-for="(item, index) in payWayList"
                            :key="index"
                            class="pay-item"
                            :class="{ active: payWayType === item.channel }"
                            @click="handleChange(item.channel)"
                        >
                            <el-image :src="item.icon" class="h-[22px] w-[22px]" />
                            <span class="ml-2 text-lg">{{ item.shorter }}</span>
                        </div>
                    </div>
                    <div class="body-qrcode">
                        <div v-loading="qrLoading" class="qr">
                            <vue-qr
                                v-show="qrCodeUrl"
                                :text="qrCodeUrl"
                                :size="200"
                            />
                        </div>
                    </div>
                </div>
            </div>

        </popup></ClientOnly>
</template>

<script setup lang="ts">
import VueQr from 'vue-qr/src/packages/vue-qr.vue'
import paymentApi from '@/api/payment'

const props = defineProps({
    // 显示状态
    show: {
        type: Boolean,
        default: false
    },
    // 订单类型
    attach: {
        type: String,
        default: ''
    },
    // 订单的ID
    orderId: {
        type: Number,
        default: 0
    },
    // 支付金额
    paidAmount: {
        type: Number,
        default: 0
    },
    // 产品名称
    productName: {
        type: String,
        default: ''
    }
})

const emits = defineEmits<{
  (event: 'close' | 'success' | 'fail'): void
}>()

// 窗口显示
const visible = ref<boolean>(false)

// 支付方式
const payWayType = ref<number>(0)
const payWayList = ref<any>([])

// 二维码值
const qrLoading = ref<boolean>(false)
const qrCodeUrl = ref<string>('')
let listenEnd: any = null

/**
 * 获取支付方式
 */
const queryPayWay = async () => {
    payWayList.value = await paymentApi.payWay()
    payWayType.value = payWayList.value[0].channel
}

/**
 * 切换支付方式
 *
 * @param type
 */
const handleChange = async (channel: number) => {
    payWayType.value = channel
    await sendPayment()
}

/**
 * 处理窗口关闭
 */
const handleClose = () => {
    if (listenEnd) {
        listenEnd()
    }
    emits('close')
    visible.value = false
}

/**
 * 发起支付请求
 */
const sendPayment = async () => {
    qrLoading.value = true
    qrCodeUrl.value = ''
    qrCodeUrl.value = await paymentApi.prepay({
        order_id: Number(props.orderId),
        pay_way: payWayType.value,
        attach: String(props.attach)
    }).finally(() => {
        qrLoading.value = false
    })

    listenPayStatus()
}

/**
 * 心跳监听支付
 */
const listenPayStatus = async () => {
    listenEnd = null
    const { start, end } = usePolling(
        async () => {
            const { status } = await paymentApi.listen({
                order_id: Number(props.orderId),
                attach: String(props.attach)
            })
            if (status === 1) {
                emits('success')
                handleClose()
                feedback.alertSuccess('支付成功')
            }
        },
        {
            key: 'payment',
            totalTime: 300 * 1000,
            callback: () => {
                emits('close')
                handleClose()
                feedback.alertWarning('支付超时！')
            }
        }
    )
    listenEnd = end
    start()
}

watch(
    () => props.show,
    async (val) => {
        visible.value = val
        if (val) {
            await queryPayWay()
            if (payWayType.value) {
                await sendPayment()
            }
        }
    }
)
</script>

<style scoped lang="scss">
.optional-body {
    display: flex;
    min-height: 250px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 6px;
    .body-sidebar {
        width: 150px;
        background-color: var(--el-bg-color-page);
        .pay-item {
            display: flex;
            align-items: center;
            padding: 18px 0;
            padding-left: 10px;
            cursor: pointer;
            &.active {
                color: var(--el-color-primary);
                background-color: #ffffff;
            }
        }
    }
    .body-qrcode {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: center;
        .qr {
            width: 200px;
            height: 200px;
            background-color: var(--el-bg-color-page);
            border-radius: 4px;
        }
    }
}
</style>
